package avicit.bdp.dds.server.master.processor;

import avicit.bdp.common.utils.SpringApplicationContext;
import avicit.bdp.common.utils.redis.RedisCacheHelper;
import avicit.bdp.dds.dispatch.enums.ExecutionStatus;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dds.common.thread.Stopper;
import avicit.bdp.dds.common.thread.ThreadUtils;
import avicit.bdp.dds.common.utils.Preconditions;
import avicit.bdp.dds.dao.entity.TaskInstance;
import avicit.bdp.dds.remote.command.Command;
import avicit.bdp.dds.remote.command.CommandType;
import avicit.bdp.dds.remote.command.TaskExecuteAckCommand;
import avicit.bdp.dds.remote.processor.NettyRequestProcessor;
import avicit.bdp.dds.remote.utils.ChannelUtils;
import avicit.bdp.dds.remote.utils.FastJsonSerializer;
import avicit.bdp.dds.server.master.cache.TaskInstanceCacheManager;
import avicit.bdp.dds.server.master.cache.impl.TaskInstanceCacheManagerImpl;
import avicit.bdp.dds.server.master.processor.queue.TaskResponseEvent;
import avicit.bdp.dds.server.master.processor.queue.TaskResponseService;
import avicit.bdp.dds.service.process.ProcessService;
import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static avicit.bdp.dds.common.Constants.SLEEP_TIME_MILLIS;

/**
 * task ack processor
 */
public class TaskAckProcessor implements NettyRequestProcessor {

    private final Logger logger = LoggerFactory.getLogger(TaskAckProcessor.class);

    /**
     * process service
     */
    private final TaskResponseService taskResponseService;

    /**
     * taskInstance cache manager
     */
    private final TaskInstanceCacheManager taskInstanceCacheManager;


    /**
     * processService
     */
    private ProcessService processService;

    public TaskAckProcessor() {
        this.taskResponseService = SpringApplicationContext.getBean(TaskResponseService.class);
        this.taskInstanceCacheManager = SpringApplicationContext.getBean(TaskInstanceCacheManagerImpl.class);
        this.processService = SpringApplicationContext.getBean(ProcessService.class);
    }

    /**
     * task ack process
     *
     * @param channel channel channel
     * @param command command TaskExecuteAckCommand
     */
    @Override
    public void process(Channel channel, Command command) {
        Preconditions.checkArgument(CommandType.TASK_EXECUTE_ACK == command.getType(), String.format("invalid command type : %s", command.getType()));
        TaskExecuteAckCommand taskAckCommand = FastJsonSerializer.deserialize(command.getBody(), TaskExecuteAckCommand.class);
        logger.info("taskAckCommand : {}", taskAckCommand);

        String workerAddress = ChannelUtils.toAddress(channel).getAddress();

        Integer ackStatus = taskAckCommand.getStatus();

        //如果sparkFlow
        String taskStr = RedisCacheHelper.getInstance().get("bdp:dds:task:" + taskAckCommand.getTaskInstanceId());
        //缓存信息是sparkFlow的虚拟节点
        if (StringUtils.isNotBlank(taskStr)) {
            TaskInstance taskInstance = JSONUtils.parseObject(taskStr, TaskInstance.class);
            taskInstance.setState(taskAckCommand.getStatus());
            taskInstance.setStartTime(taskAckCommand.getStartTime());
            taskInstance.setHost(workerAddress);
            taskInstance.setExecutePath(taskAckCommand.getExecutePath());
            taskInstance.setLogPath(taskAckCommand.getLogPath());
            RedisCacheHelper.getInstance().set("bdp:dds:task:" + taskAckCommand.getTaskInstanceId(), JSONUtils.toJson(taskInstance));
            return;
        }

        taskInstanceCacheManager.cacheTaskInstance(taskAckCommand);

        // TaskResponseEvent
        TaskResponseEvent taskResponseEvent = TaskResponseEvent.newAck(ackStatus,
                taskAckCommand.getStartTime(),
                workerAddress,
                taskAckCommand.getExecutePath(),
                taskAckCommand.getLogPath(),
                taskAckCommand.getTaskInstanceId());

        taskResponseService.addResponse(taskResponseEvent);

        while (Stopper.isRunning()) {
            TaskInstance taskInstance = processService.findTaskInstanceById(taskAckCommand.getTaskInstanceId());

            if (taskInstance != null && ExecutionStatus.of(ackStatus).typeIsRunning()) {
                break;
            }
            ThreadUtils.sleep(SLEEP_TIME_MILLIS);
        }

    }

}
